<?php
namespace app\common\library;

class DHgateOAuth
{
    private $clientId;
    private $clientSecret;
    private $redirectUri;
    private $authUrl = 'https://secure.dhgate.com/dop/oauth2/authorize';
    private $tokenUrl = 'https://secure.dhgate.com/dop/oauth2/access_token';

    public function __construct($clientId, $clientSecret, $redirectUri) {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
        $this->redirectUri = $redirectUri;
    }

    /**
     * 生成授权链接并跳转
     */
    public function getAuthCode() {
        $state = bin2hex(random_bytes(16)); // 防CSRF
        $_SESSION['oauth_state'] = $state;

        $params = [
            'response_type' => 'code',
            'client_id' => $this->clientId,
            'redirect_uri' => $this->redirectUri,
            'scope' => 'basic', // 按需修改
            'state' => $state,
            'view' => 'web'
        ];

        header('Location: ' . $this->authUrl . '?' . http_build_query($params));
        exit;
    }

    /**
     * 用Authorization Code换取Access Token
     */
    public function getAccessToken($code) {
        $params = [
            'grant_type' => 'authorization_code',
            'code' => $code,
            'client_id' => $this->clientId,
            'client_secret' => $this->clientSecret,
            'redirect_uri' => $this->redirectUri
        ];

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->tokenUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }

}